﻿using KingsSharp.Common;
using KingsSharp.Common.Extensions;
using KingsSharp.Core.Data.Entity;
using KingsSharp.Core.Data.Extensions;
using KingsSharp.Web.Mvc.Binders;
using KingsSharp.Web.UI;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;

namespace CRM.Admin.Areas.Sys.Controllers
{
    public class OrganizationController : Controller
    {
        /// <summary>
        /// 组织机构业务契约
        /// </summary>
        public IOrganizationService _organizationService { get; set; }

        public ActionResult OrganizationIndex()
        {
            return View();
        }
        public ActionResult OrganizationAdd()
        {
            return View();
        }
        public ActionResult OrganizationEdit(Guid OrganizationId)
        {
            OrganizationId.CheckNotEmpty("OrganizationId");
            var dto = _organizationService.ItemOrganization.Include(a => a.Parent).
                Where(a => a.Id == OrganizationId).FirstOrDefault().MapTo<OrganizationDto>();
            return View(dto);
        }
        public ActionResult OrganizationTree()
        {
            var zTree = GetOrganizationTree();

            return View((object)zTree.ToJsonString(true));
        }
        #region 数据功能
        [HttpPost]
        public ActionResult OrganizationInsert([ModelBinder(typeof(JsonBinder<OrganizationDto>))] OrganizationDto dtos)
        {
            dtos.CheckNotNull("dtos");
            dtos.Id = Guid.NewGuid();
            var result = _organizationService.InsertOrganization(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "机构“{0}”添加成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        [HttpPost]
        public ActionResult OrganizationUpdate([ModelBinder(typeof(JsonBinder<OrganizationDto>))] OrganizationDto dtos)
        {
            dtos.CheckNotNull("dtos");
            var result = _organizationService.UpdateOrganization(dtos);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "机构“{0}”更新成功。".FormatWith(dtos.Name);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        [HttpPost]
        public ActionResult OrganizationDelete(Guid OrganizationId, string OrganizationName)
        {
            var result = _organizationService.DeleteOrganization(OrganizationId);
            string msg = result.Message ?? result.ResultType.ToDescription();
            AjaxResultType msgType = result.ResultType.ToAjaxResultType();
            if (msgType != AjaxResultType.Error)
            {
                msg = "机构“{0}”删除成功。".FormatWith(OrganizationName);
            }
            return Json(new AjaxResult(msg, msgType));
        }
        public ActionResult GetOrganizationGridData()
        {
            var data = _organizationService.ItemOrganization.Include(a => a.Children)
                .Include(a => a.Children).Include(a => a.Parent)
                 .Where(a => a.IsDeleted == false).OrderBy(a => a.Order).ToList();

            ICollection<OrganizationTreeView> viewdata = data.RenderTree<Organization, OrganizationTreeView>(data.Where(a => a.Parent == null).ToList(), (catalog, level) =>
            {
                return new OrganizationTreeView()
                {
                    Name = catalog.Name,
                    Id = catalog.Id.ToString(),
                    Remark = catalog.Remark,
                    Code = catalog.Code,
                    Order = catalog.Order
                };
            }, (catalog, sources) =>
            {
                return sources.Where(a => a.Parent != null
                    && a.Parent.Id == catalog.Id).ToList();
            }, (parentNode, newNode) =>
            {
                if (parentNode.children == null)
                {
                    parentNode.children = new List<OrganizationTreeView>();
                }
                parentNode.children.Add(newNode);
            });
            return Json(viewdata, JsonRequestBehavior.AllowGet);
        }

        public ICollection<ZTreeNode> GetOrganizationTree()
        {
            var data = _organizationService.ItemOrganization.Include(a => a.Children)
                .Where(a => a.IsDeleted == false).OrderBy(a => a.Order).ToList();
            var zTree = data.RenderTree<Organization, ZTreeNode>(data.Where(a => a.Parent == null).ToList(), (catalog, level) =>
            {
                return new ZTreeNode()
                {
                    Id = catalog.Id.ToString(),
                    Name = catalog.Name,
                    Order = catalog.Order,
                    Pid = catalog.ParentOrganizationId.ToString(),
                    Open = level < 2
                };
            }, (catalog, sources) =>
            {
                return sources.Where(a => a.Parent != null
                    && a.Parent.Id == catalog.Id).ToList();
            }, (parentNode, newNode) =>
            {
                if (parentNode.Children == null)
                {
                    parentNode.Children = new List<ZTreeNode>();
                }
                parentNode.Children.Add(newNode);
            });
            return zTree;
        }
        #endregion
    }
    public class OrganizationTreeView
    {
        public string Name { get; set; }

        public string Id { get; set; }

        public string Code { get; set; }

        public int Order { get; set; }

        public string Remark { get; set; }
        public ICollection<OrganizationTreeView> children { get; set; }
    }
}